package application;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import fetch.nokiasportstracker.KMLParser;
import utils.config.Config;

public class MainParser {
	/*
	 * This class takes in input nst kml files and store them in a database
	 */
	
	/*
	 * SAREBBE DA TESTARE SE FUNZIONA ANCORA
	 */
	
	private String BASE_DIR;
	private String OUT_DB;
	
	public static void main(String[] args) throws Exception {
		MainParser mp = new MainParser();
		mp.parse();
	}
	
	
	public MainParser() {
		Config config = new Config(this.getClass().getSimpleName()+".ser"); 
		BASE_DIR = (String)config.get("BASE_DIR");
		OUT_DB = (String)config.get("OUT_DB");
	}
	
	public void parse() throws Exception {
		KMLParser p = new KMLParser();
		
		File fdir = new File(BASE_DIR);
		File[] files = fdir.listFiles();
		
		Class.forName("com.mysql.jdbc.Driver").newInstance();
	    Connection c = DriverManager.getConnection(OUT_DB);
	    Statement s = c.createStatement();
	    //to speed up 
		String query = "LOCK TABLES data WRITE";
		s.executeQuery(query);	
		
		for(int i=0; i<files.length;i++) {
			if(files[i].getName().endsWith(".kml")){
				String insert = p.parse(BASE_DIR+"/"+files[i].getName());
				
			}
			
		}
		
		//close db connections
		s.executeQuery("UNLOCK TABLES");
		s.close();
	    c.close();
	}

}
